package com.myframework.utils.configutil;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class DOMUtil {

	/**
	 * A reference to the DocumentBuilderFactory that we'll use to get instances
	 * of DocumentBuilder objects.
	 */
	protected static DocumentBuilderFactory	dbFactory	= null;

	/**
	 * Parse the content of the given InputStream as an XML document and return a
	 * new DOM Document object.
	 * 
	 * @param stream
	 *          InputStream containing the content to be parsed.
	 * @return A new DOM Document object.
	 * @throws java.io.IOException
	 *           If any I/O errors occur.
	 * @throws org.xml.sax.SAXException
	 *           If any parse errors occur.
	 * @throws ParserConfigurationException
	 *           If a DocumentBuilder cannot be created due to a configuration
	 *           problem.
	 */
	public static Document parse(InputStream stream) throws SAXException, IOException, ParserConfigurationException {
		return getDocumentBuilder().parse(stream);
	}

	/**
	 * Get the instance of the DocumentBuilderFactory (if we haven't already), and
	 * then use it to create a DocumentBuilder
	 * 
	 * @return A new DocumentBuilder instance.
	 * @throws ParserConfigurationException
	 *           If a DocumentBuilder cannot be created due to a configuration
	 *           problem.
	 */
	private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {

		DocumentBuilder db = null;

		// Get an instance of a DocumentBuilderFactory if we haven't already
		if (dbFactory == null) {
			dbFactory = DocumentBuilderFactory.newInstance();
			dbFactory.setNamespaceAware(true);
		}

		// Make sure we don't allow more than one thread to touch
		// the DocumentBuilderFactory concurrently since the underlying
		// implementation is not guaranteed to be thread safe
		synchronized (dbFactory) {

			db = dbFactory.newDocumentBuilder();

		}

		DTDResolver dtdr = new DTDResolver();
		db.setEntityResolver(dtdr);
		return db;
	}

}
